package com.tom.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zx
 * @date 2024-09-27 21:01
 */
public class MyServer1 {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8000));
        serverSocketChannel.configureBlocking(false);// 解决连接阻塞

        List<SocketChannel> channelList = new ArrayList<>();

        ByteBuffer buffer = ByteBuffer.allocate(20);

        // 3. 接受client的连接
        while (true) {
            // 4. ScoketChannle 代表 服务端与Client链接的一个通道
            System.out.println("等待连接服务器...");
            SocketChannel socketChannel = serverSocketChannel.accept();// 阻塞 程序等待client
            System.out.println("服务器已经连接..."+socketChannel);
            if(socketChannel !=null){
                socketChannel.configureBlocking(false);//解决通信阻塞
                channelList.add(socketChannel);
            }

            // 5. client与服务端 通信过程 NIO代码
            for (SocketChannel channel : channelList) {
                int read = channel.read(buffer); //读取到客户端发送的信息猜执行下面的代码
                if(read > 0){
                    System.out.println("开始实际的数据通信....");
                    buffer.flip();
                    // CharBuffer decode = Charset.forName("UTF-8").decode(buffer);
                    CharBuffer decode = StandardCharsets.UTF_8.decode(buffer);
                    System.out.println("decode.toString() = " + decode.toString());
                    buffer.clear();
                    System.out.println("通信已经结束....");
                }
            }
        }
    }
}
